package cn.passlink.www.Utils;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.FilenameUtils;
import org.springframework.lang.NonNull;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
@Slf4j
public class imgUpload {
    private static final Map<String, File> dirMap = new HashMap<>();

    /**
     * 上传图片
     * @param file 文件流对象
     * @param realpath 文件存放路径
     * @return
     */
    public static String inputUploadFile(MultipartFile file, String realpath) {
        String filename = file.getOriginalFilename();//原文件名
        String extname = FilenameUtils.getExtension(filename);//文件后缀
        String allowImgFormat = "gif,jpg,jpeg,png";
//        检测名字
        if(filename==null || filename.isEmpty() || filename.length()>=30){
            log.error("filename不符合要求");
            return "NOT_IMAGE";
        }
        String regex = "[#\\\\/:*?\"<>|]";
        boolean containsSpecialCharacters = filename.matches(regex);

        if (containsSpecialCharacters) {
            log.error("filename不符合要求");
            return "NOT_IMAGE";
        }

//        检查后缀
        if ( extname.isEmpty() || !allowImgFormat.contains(extname.toLowerCase()) ) {
            log.error("filename不符合要求");
            return "NOT_IMAGE";
        }
// 重命名文件
        filename = Math.abs(file.getOriginalFilename().hashCode()) + RandomUtils.createRandomString(10) + "." + extname;

        // 创建文件流
        try (InputStream input = file.getInputStream()) {
            // 判断目录是否存在不存在则创建目录
            getDir(realpath);
            // 对上传的图片文件进行压缩处理
            Thumbnails.of(input)
                    .size(800, 480)  // 设置输出图片的尺寸
                    .outputQuality(0.2f) // 设置输出质量
                    .toFile(new File(realpath + filename)); // 压缩并保存到指定路径

            return filename;
        } catch (IOException e) {
            log.error("UPLOAD_ERROR",e);
            return "UPLOAD_ERROR";
        }

    }


    /**
     * 判断目录是否存在不存在则创建目录
     * @param dirName
     * @return
     */

    private static File getDir(@NonNull String dirName) {
        File dir = dirMap.get(dirName);
        if (dir != null) {

            return dir;
        }

        dir = new File(dirName);
        if (!dir.exists()) {
            log.info("创建文件夹");
            dir.mkdirs();
        }
        dirMap.putIfAbsent(dirName, dir);
        return dir;
    }

    /**
     * 获取网站域名地址
     * @param request
     * @return
     */
    public static String domain(HttpServletRequest request) {
        return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
    }


}
